package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import io.minio.*;
import io.minio.errors.*;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioConstantProperties minioConstantProperties;

    /**
     * 上传文件到MinIO服务器
     *
     * @param file 要上传的文件
     * @return 返回上传成功后的文件URL
     * @throws RuntimeException 如果上传过程中发生错误，则抛出运行时异常
     */
    /*@Override
    public String upload(MultipartFile file) {
        // 初始化URL为空字符串，用于后续存储上传后的文件URL
        String url = "";

        try {
            // 构建MinIO客户端实例
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioConstantProperties.getEndpointUrl())
                            .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())
                            .build();

            // 检查存储桶是否存在
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            if (!found) {
                // 如果存储桶不存在，则创建新的存储桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            } else {
                // 如果存储桶已存在，则打印提示信息
                System.out.println("Bucket " + minioConstantProperties.getBucketName() + " already exists.");
            }

            // 生成唯一的文件名，并拼接文件后缀
            String fileName = UUID.randomUUID().toString()
                    .replaceAll("-", "") + "." +
                    FilenameUtils.getExtension(file.getOriginalFilename());

            // 将文件上传到MinIO服务器
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(
                            minioConstantProperties.getBucketName()
                    ).object(fileName).stream(
                            file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());

            // 构建并返回文件的URL
            url = minioConstantProperties.getEndpointUrl()
                    +"/"+minioConstantProperties.getBucketName()+"/"+fileName;
        } catch (ErrorResponseException e) {
            throw new RuntimeException(e);
        } catch (InsufficientDataException e) {
            throw new RuntimeException(e);
        } catch (InternalException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (InvalidResponseException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (ServerException e) {
            throw new RuntimeException(e);
        } catch (XmlParserException e) {
            throw new RuntimeException(e);
        }
        return url;
    }*/

    @Override
    public String upload(MultipartFile file) {
        String url = "";
        try {
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioConstantProperties.getEndpointUrl())
                            .credentials(minioConstantProperties.getAccessKey(),
                                    minioConstantProperties.getSecreKey())
                            .build();
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket 'asiatrip' already exists.");
            }
            String fileName= UUID.randomUUID().toString().replaceAll("-","")
                    +"."+FilenameUtils.getExtension(file.getName());
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioConstantProperties.getBucketName()).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());

            url = minioConstantProperties.getEndpointUrl()
                    +"/"+minioConstantProperties.getBucketName()+"/"+fileName;
        } catch (ErrorResponseException e) {
            throw new RuntimeException(e);
        } catch (InsufficientDataException e) {
            throw new RuntimeException(e);
        } catch (InternalException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (InvalidResponseException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (ServerException e) {
            throw new RuntimeException(e);
        } catch (XmlParserException e) {
            throw new RuntimeException(e);
        }
        return url;
    }
}
